import { defineStore } from 'pinia'
// import axios from 'axios'
import request from '@/utils/request'
import { CategoryItem, ApiResponse, TopCategory, SubCategory } from '@/types/data'
import { topCategory } from '../constants'

// 对默认初始值进行一下改造, 改造成与status中类型相符的类型
const defaultTopCategory = topCategory.map(item => {
  return {
    name: item
  }
})

export default defineStore('category', {
  state: () => {
    return {
      list: defaultTopCategory as CategoryItem[],
      // 顶级分类
      topCategory: {} as TopCategory,
      // 二级分类
      subCategory: {} as SubCategory,
    }
  },
  getters: {},
  actions: {
    async fetchAllCategoryList() {
      // const res = await axios.get('http://pcapi-xiaotuxian-front.itheima.net/home/category/head')
      const res = await request.get<ApiResponse<CategoryItem[]>>('/home/category/head')
      // todo 这里对后台返回回来的数据进行加工，新增一个属性 open 标记弹层的显示或者隐藏
      res.data.result?.forEach(item => item.open = false)
      if (res.data.result) {
        this.list = res.data.result
      }
    },
    // 鼠标hover时，显示当前项的弹层
    show(id: string) {
      this.list.forEach(item => {
        if (item.id === id) item.open = true
      })
    },
    // 鼠标离开时，隐藏当前项的弹层
    hide(id: string) {
      this.list.forEach(item => {
        if (item.id === id) item.open = false
      })
    },
    // 获取一级分类
    async fetchTopCategory(id: string) {
      try {
        const res = await request.get<ApiResponse<TopCategory>>('/category', {
          params: {
            id,
          },
        })
        if (res.data.result) {
          this.topCategory = res.data.result
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 获取二级分类的数据
    async fetchSubfilter(id: string) {
      try {
        const res = await request.get<ApiResponse<SubCategory>>('/category/sub/filter', {
          params: { id }
        })
        if (res.data.result) {
          this.subCategory = res.data.result
        }
      } catch (error) {
        console.error(error);
      }
    }
  }
}) 